/**
 * 
 */
package com.jxc.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

/**
 * 各种单号生成
 * 
 * @author Tino
 * 
 */
public class SerialUtils {
	public final static ConcurrentHashMap<ListType, String> serialMap = new ConcurrentHashMap<ListType, String>();

	static {
		String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
		for (ListType lt : ListType.values()) {
			serialMap.put(lt, lt.getSign() + "-" + today + "-00001");
		}
	}

	/**
	 * 获取单号
	 * 
	 * @param sign
	 * @return
	 */
	public static synchronized String serial(String sign) {
		if (sign == null)
			return null;
		ListType lt = ListType.fromSign(sign);
		if (lt == null)
			return null;
		String lastSignSerial = serialMap.get(lt);
		String[] lastSignSerials = lastSignSerial.split("-");
		String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
		if (Integer.parseInt(lastSignSerials[1]) < Integer.parseInt(today)) {
			lastSignSerials[1] = today;
			lastSignSerials[2] = "00001";
		} else {
			Integer increase = Integer.parseInt(lastSignSerials[2]);
			increase += 1;
			lastSignSerials[2] = String.valueOf(increase);
			lastSignSerials[2] = "00000".substring(0, 5 - lastSignSerials[2].length()) + lastSignSerials[2];
		}
		serialMap.put(lt, StringUtils.join(lastSignSerials, "-"));
		return StringUtils.join(lastSignSerials, "-");
	}

	public static void main(String[] args) {
		System.out.println(SerialUtils.serial("DB"));
	/*	System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		System.out.println(SerialUtils.serial("DB"));
		
		System.out.println(SerialUtils.serial("BD"));
		System.out.println(SerialUtils.serial("BS"));
		System.out.println(SerialUtils.serial("RK"));
		System.out.println(SerialUtils.serial("RKTH"));
		System.out.println(SerialUtils.serial("XS"));
		System.out.println(SerialUtils.serial("XSTH"));
		
		System.out.println(SerialUtils.serial("AB"));
		System.out.println(SerialUtils.serial(null));
		
		System.out.println(SerialUtils.serial("HY"));*/
	}
}
